//
//  EventDetailViewController.m
//  FootPrint
//
//  Created by 秦 东方 on 3/19/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "EventDetailViewController.h"
#import "UserGridCell.h"
#import "UserMsgCell.h"
#import "FriendMsgCell.h"
#import "FriendDetailViewController.h"
#import "PIODetailViewController.h"
#import "TemplateManager.h"
#import "GReminder.h"
#import "MsgManager.h"

@interface EventDetailViewController ()

@end

@implementation EventDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _parser = [[EventParser alloc] init];
        _parser.delegate = self;
        
        _canModifyFriends = [[NSMutableArray alloc] initWithCapacity:2];
        _eventMode = eModeMidifyEvent;
        
        _formatter = [[NSDateFormatter alloc] init];
        [_formatter setDateFormat:@"MM月dd日\nHH点mm分"];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    
    [_canModifyFriends release];
    [_friendList release];
    [_formatter release];
    self.msgArr = nil;
    [_builder release];
    self.eventInfo = nil;
    [_parser release];
    [_gridScroll release];
    [_userListView release];
    [_msgText release];
    [_contentScroll release];
    [_msgTableList release];
    [_eventNameLabel release];
    [_shopBtn release];
    [_eventIcon release];
    [_dateBtn release];
    [_btnSeeMsg release];
    [_setTopBtn release];
    [_memberLabel release];
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _gridScroll.gridDelegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    UITapGestureRecognizer * tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOnIcon)] autorelease];
    [_eventIcon addGestureRecognizer:tapGesture];
    
    _eventNameLabel.enabled = (_eventMode == eModeCreateEvent);
    _btnSeeMsg.hidden = _memberLabel.hidden = _setTopBtn.hidden = YES;
    if (_eventNameLabel.enabled) {
        [_eventNameLabel becomeFirstResponder];
    }
    
    _dateBtn.titleLabel.numberOfLines = 2;
    
    UIImage* imgNormal =[[UIImage imageNamed:@"btn_bg_normal.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    UIImage* imgPress =[[UIImage imageNamed:@"btn_bg_press.png"] stretchableImageWithLeftCapWidth:10 topCapHeight:0];
    
    [_btnSeeMsg setBackgroundImage:imgNormal forState:UIControlStateNormal];
    [_btnSeeMsg setBackgroundImage:imgPress forState:UIControlStateHighlighted];
    
}

- (void)setEventMode:(eEventMode)eventMode
{
    if (_eventMode != eventMode) {
        _eventMode = eventMode;
        _eventNameLabel.enabled = (_eventMode == eModeCreateEvent);
    }
    _btnSeeMsg.hidden = _memberLabel.hidden = _setTopBtn.hidden = YES;
    
    if (_eventNameLabel.enabled) {
        [_shopBtn setTitle:@"点击选择商家" forState:UIControlStateNormal];
        [_eventNameLabel becomeFirstResponder];
    } else {
        if (![self canModify]) {
            _eventIcon.userInteractionEnabled = NO;
            _shopBtn.userInteractionEnabled = NO;
            _dateBtn.userInteractionEnabled = NO;
            _gridScroll.userInteractionEnabled = NO;
        } else {
            _eventIcon.userInteractionEnabled = YES;
            _shopBtn.userInteractionEnabled = YES;
            _dateBtn.userInteractionEnabled = YES;
            _gridScroll.userInteractionEnabled = YES;
        }
    }

    [self checkInitBuilder];
    [self reloadGridScroll];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _eventNameLabel) {
        if (_eventNameLabel.text.length == 0) {
            [[iToast makeText:@"名字不能为空"] show];
            return NO;
        }
        [_eventNameLabel resignFirstResponder];
    }
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tapOnIcon
{
    if (_eventMode == eModeCreateEvent) {
        PickIconViewController * pickVc = [[[PickIconViewController alloc] initWithNibName:@"PickIconViewController" bundle:nil] autorelease];
        pickVc.pickMode = YES;
        pickVc.pickDelegate = self;
        [self.navigationController pushViewController:pickVc animated:YES];
    }
}

- (IBAction)dismiss {
    if (self.navigationController.viewControllers.count > 1) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self.navigationController dismissModalViewControllerAnimated:YES];
    }
}

- (IBAction)switchMode:(id)sender
{
    UIButton * btn = (UIButton*)sender;
    btn.selected = !btn.isSelected;
    
    CGRect oldRc = _userListView.frame;
    if (btn.isSelected)
    {
        _btnSeeMsg.titleLabel.text = @"查看留言";
        
        oldRc.origin.y = CGRectGetMinY(_msgTableList.frame) - CGRectGetHeight(oldRc);
        
        [[GAlertLoadingView sharedAlertLoadingView] show];
        [_parser updateMsgWithId:_eventId];
    }
    else
    {
        _btnSeeMsg.titleLabel.text = @"查看人物";
        oldRc.origin.y = CGRectGetHeight(_contentScroll.frame) - CGRectGetHeight(oldRc);
    }
    
    [UIView animateWithDuration:.3 animations:^{
        _userListView.frame = oldRc;
    }];
}

- (IBAction)sendMsg
{
    if (_msgText.text.length == 0) {
        [[iToast makeText:@"留言不能为空！"] show];
        return;
    }
    if (![GConfig hasLogin]) {
        [[iToast makeText:@"请先登陆才能留言！"] show];
        return;
    }
    
    [[GAlertLoadingView sharedAlertLoadingView] show];
    
    [_parser addEventBoardMsg:_msgText.text forEventId:_eventId andUserId:[GConfig getUserId]];
    _msgText.text = @"";
    [_msgText resignFirstResponder];
}

- (IBAction)more
{
    UIActionSheet * actionSheet = nil;
    
    if ([self isEventOwner]) {
        if (_builder || _canModifyFriends.count > 0) {
            if (_eventMode == eModeCreateEvent) {
                actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                          delegate:self
                                                 cancelButtonTitle:@"取消"
                                            destructiveButtonTitle:nil
                                                 otherButtonTitles:@"确定", @"加载模板", @"存为模板", nil];
            } else {
                if ([self canModify]) {
                    actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                              delegate:self
                                                     cancelButtonTitle:@"取消"
                                                destructiveButtonTitle:nil
                                                     otherButtonTitles:@"确定", @"存为模板", @"设置提醒", @"删除", nil];
                } else {
                    actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                              delegate:self
                                                     cancelButtonTitle:@"取消"
                                                destructiveButtonTitle:nil
                                                     otherButtonTitles:@"存为模板", @"删除", nil];
                }
            }
        } else {
            if (_eventMode == eModeCreateEvent) {
                actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                          delegate:self
                                                 cancelButtonTitle:@"取消"
                                            destructiveButtonTitle:nil
                                                 otherButtonTitles:@"加载模板", @"存为模板", nil];
            } else {
                actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                          delegate:self
                                                 cancelButtonTitle:@"取消"
                                            destructiveButtonTitle:nil
                                                 otherButtonTitles:@"存为模板", @"设置提醒", @"删除", nil];
            }
        }
    } else {
        actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                  delegate:self
                                         cancelButtonTitle:@"取消"
                                    destructiveButtonTitle:nil
                                         otherButtonTitles:@"存为模板", @"设置提醒", nil];
    }
    
    [actionSheet showInView:self.navigationController.view];
    [actionSheet release];
}

- (IBAction)changeDate:(id)sender
{
    if (self.eventInfo) {
        CalendarViewController * calVC = [[[CalendarViewController alloc] initWithNibName:@"CalendarViewController" bundle:nil] autorelease];
        NSDate * date = [[GToolUtil sharedInstance].dateFormatter dateFromString:[NSString stringWithFormat:@"%lld", self.eventInfo.time]];
        [calVC calPickModeWithDate:date update:NO];
        calVC.pickDelegate = self;
        [self.navigationController pushViewController:calVC animated:YES];
        [calVC updateCalendarData];
    }
}

- (IBAction)changePOI:(id)sender
{
    if ([self isEventOwner]) {
        PoiFrameViewController* poiFrame = [[[PoiFrameViewController alloc] initWithNibName:@"PoiFrameViewController" bundle:nil] autorelease];
        [poiFrame setMode:1];
        poiFrame.selDelegate = self;
        [self.navigationController pushViewController:poiFrame animated:YES];
        
        
    } else {
        PIODetailViewController * poiVC = [[[PIODetailViewController alloc] initWithNibName:@"PIODetailViewController" bundle:nil] autorelease];
        [self.navigationController pushViewController:poiVC animated:YES];
        [poiVC updatePOIInfo:self.eventInfo.merchant];
    }
}

- (IBAction)topSwitch:(id)sender
{
    NSDictionary * eventMsg = [self makePushMsg];
    
    if (_setTopBtn.isSelected) {
        [[MsgManager sharedInstance] removeMsg:eventMsg];
        [[iToast makeText:@"关注已删除"] show];
    } else {
        [[MsgManager sharedInstance] addMsg:eventMsg];
        [[iToast makeText:@"成功添加关注"] show];
    }
    
    _setTopBtn.selected = !_setTopBtn.isSelected;
}

- (void)requestById:(long long)eventId
{
    _eventId = eventId;
    [[GAlertLoadingView sharedAlertLoadingView] show];
    
    [_parser updateEventWithId:_eventId];
}

- (BOOL) isEventOwner
{
    return ([GConfig getUserId] > 0 && ([GConfig getUserId] == self.eventInfo.owner.id || eModeCreateEvent == _eventMode ));
}

- (BOOL) canModify
{
    if (_eventMode == eModeCreateEvent || nil == _eventInfo) {
        return YES;
    }
    
    long long modifyTime = _eventInfo.time;
    if ([_builder hasTime]) {
        modifyTime = [_builder time];
    }
    
    NSDate * date = [[GToolUtil sharedInstance].dateFormatter dateFromString:[NSString stringWithFormat:@"%lld", modifyTime]];
    if (NSOrderedAscending == [date compare:[NSDate date]]) {
        return NO;
    }
    return YES;
}

- (void) createWithFriendList:(NSArray*)friends
{
    [_friendList release];
    _friendList = [[NSMutableArray arrayWithArray:friends] retain];
    
    self.eventMode = eModeCreateEvent;
    
    [self reloadGridScroll];
}

- (void) createWithTemplate:(EventMessage*)templateMsg
{
    [self didSelTemplate:templateMsg];
}


#pragma mark - UIActionSheetDelegate
                               
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString * title = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([title isEqualToString:@"确定"])
    {
        if (eModeMidifyEvent == _eventMode) {
            [[GAlertLoadingView sharedAlertLoadingView] show];
            if (_builder) {
                [_parser modifyEvent:[[_builder clone] build] forUser:[GConfig getUserId]];
            }
            if (_canModifyFriends.count > 0) {
                NSMutableArray * idArr = [[[NSMutableArray alloc] initWithCapacity:_canModifyFriends.count] autorelease];
                for (EventMessage_UserStatus * status in _canModifyFriends) {
                    [idArr addObject:[NSNumber numberWithLongLong:status.user.id]];
                }
                [_parser modifyEvent:_eventId andUserId:[GConfig getUserId] addMember:idArr removeMember:nil];
            }
        } else {
            
            if (_eventNameLabel.text.length == 0) {
                [[iToast makeText:@"事件名不能为空"] show];
                return;
            }
            
            [[GAlertLoadingView sharedAlertLoadingView] show];
            if (_builder) {
                [_builder setTitle:_eventNameLabel.text];
                
                NSMutableArray * userList = [NSMutableArray arrayWithObject:[[[[EventMessage_UserStatus builder] setStatus:eStatAccept] setUser:[GToolUtil ownerMsg]] build]];
                for (UserMessage * status in _friendList) {
                    if ([status isKindOfClass:[UserMessage class]]) {
                        EventMessage_UserStatus * realStatus = [[[[EventMessage_UserStatus builder] setStatus:eStatWait] setUser:status] build];
                        [userList addObject:realStatus];
                    } else {
                        [userList addObject:status];
                    }
                }
                for (EventMessage_UserStatus * status in _canModifyFriends) {
                    [userList addObject:status];
                }
                [_builder setUserStatusArray:userList];
                [_parser createEvent:[[_builder clone] build] forUser:[GConfig getUserId]];
            }
        }
    }
    else if ([title isEqualToString:@"加载模板"])
    {
        TemplateViewController * templateVC = [[[TemplateViewController alloc] initWithNibName:@"TemplateViewController" bundle:nil] autorelease];
        templateVC.selDelegate = self;
        [self.navigationController pushViewController:templateVC animated:YES];
    }
    else if ([title isEqualToString:@"存为模板"])
    {
        EventMessage * templateMsg = self.eventInfo;
        if (_builder) {
            [_builder setTitle:_eventNameLabel.text];
            NSMutableArray * userList = [NSMutableArray array];
            for (UserMessage * status in _friendList) {
                if ([status isKindOfClass:[UserMessage class]]) {
                    EventMessage_UserStatus * realStatus = [[[[EventMessage_UserStatus builder] setStatus:eStatWait] setUser:status] build];
                    if (realStatus.user.id != [GConfig getUserId]) [userList addObject:realStatus];
                } else {
                    if (status.id != [GConfig getUserId]) [userList addObject:status];
                }
            }
            for (EventMessage_UserStatus * status in _canModifyFriends) {
                [userList addObject:status];
            }
            [_builder setUserStatusArray:userList];
            
            templateMsg = [[_builder clone] build];
        }
        
        if (templateMsg.title.length == 0) {
            [[iToast makeText:@"事件名不能为空"] show];
            return;
        }
        
        if ([[TemplateManager sharedInstance] saveTemplate:templateMsg forName:templateMsg.title]) {
            [[iToast makeText:@"模板已保存"] show];
        } else {
            [[iToast makeText:@"模板保存失败"] show];
        }
    }
    else if ([title isEqualToString:@"设置提醒"])
    {
        NSDate * eventDate = [[GToolUtil sharedInstance].dateFormatter dateFromString:[NSString stringWithFormat:@"%lld", _eventInfo.time]];
        if ([eventDate timeIntervalSinceNow] < 0) {
            [[iToast makeText:@"事件已过期"] show];
        } else {
            ReminderViewController * reminder = [[[ReminderViewController alloc] initWithNibName:@"ReminderViewController" bundle:nil] autorelease];
            reminder.reminderMode = eReminderPickMode;
            reminder.reminderDelegate = self;
            [self.navigationController pushViewController:reminder animated:YES];
            [reminder updateTitleWithEvent:[NSString stringWithFormat:@"%lld", _eventId] andAimedDate:eventDate];
        }
    }
    else if ([title isEqualToString:@"删除"])
    {
        [_parser cancelEvent:_eventId forUser:[GConfig getUserId]];
    }
}

- (void) reloadGridScroll
{
    NSInteger aceptCnt = 0;
    
    NSMutableArray * userViews = [[[NSMutableArray alloc] initWithCapacity:_friendList.count] autorelease];
    for (int i = 0; i < _friendList.count; i++)
    {
        EventMessage_UserStatus * userStat = [_friendList objectAtIndex:i];
        
        UserGridCell * cell = [[[UserGridCell alloc] initWithFrame:CGRectMake(0, 0, 80, 80)] autorelease];
        
        if ([userStat isKindOfClass:[UserMessage class]]) {
            [cell updateUserMessage:(UserMessage*)userStat];
        } else {
            [cell updateUserState:userStat];
            if (userStat.status == 0) {
                aceptCnt++;
            }
        }
        
        [userViews addObject:cell];
    }
    
    for (int i = 0; i < _canModifyFriends.count; i++)
    {
        EventMessage_UserStatus * userStat = [_canModifyFriends objectAtIndex:i];
        
        UserGridCell * cell = [[[UserGridCell alloc] initWithFrame:CGRectMake(0, 0, 80, 80)] autorelease];
        [cell updateUserState:userStat];
        [userViews addObject:cell];
    }
    
    if ([self isEventOwner]) {
        UserGridCell * cell = [[[UserGridCell alloc] initWithFrame:CGRectMake(0, 0, 80, 80)] autorelease];
        [cell.userIcon setLocalImageName:@"add_merchant.png"];
        [userViews addObject:cell];
    }
    
    _gridScroll.cells = userViews;
    
    _memberLabel.text = [NSString stringWithFormat:@"%d/%d", aceptCnt, (_friendList.count+_canModifyFriends.count)];
}

- (NSDictionary*) makePushMsg
{
    if (nil == _eventInfo) {
        return nil;
    }
    
    NSString * imgUrl = nil;
    if (!_eventInfo.image.isSys) {
        if ([[ImageManager sharedInstance] imageExistForId:_eventInfo.image.id]) {
            imgUrl = [[ImageManager sharedInstance] imageFileForImageId:_eventInfo.image.id];
        } else {
            imgUrl = _eventInfo.image.imageUrl;
        }
    } else {
        imgUrl = [NSString stringWithFormat:@"sys_%04lld", _eventInfo.image.id];
    }
    return [MsgManager makeEventMsg:self.eventId andTitle:self.eventInfo.title andUrl:imgUrl];
}


#pragma mark - EventParserDelegate

- (void) didRecieveEventInfo:(EventQueryByIdResponseMessage*)event
{
    [[GAlertLoadingView sharedAlertLoadingView] hide];
    
    if (event && event.resultCode == 0)
    {
        [_canModifyFriends removeAllObjects];
        
        self.eventInfo = event.event;
        self.eventId = self.eventInfo.id;
        
        if (_eventMode == eModeCreateEvent) {
            [self topSwitch:nil];
        }
        
        self.eventMode = eModeMidifyEvent;
        
        [_builder release];
        _builder = nil;
        [self checkInitBuilder];
        
        [self refreshDisplay];

        _btnSeeMsg.hidden = _memberLabel.hidden = NO;
        
        NSDictionary * eventMsg = [self makePushMsg];
        _setTopBtn.hidden = (nil == eventMsg);
        _setTopBtn.selected =  [[MsgManager sharedInstance] isMsgExist:eventMsg];
    }
}

- (void) didRecieveEventMsg:(EventBoardQueryResponseMessage*)event
{
    //NSLog(@"留言板 %@", event);
    [[GAlertLoadingView sharedAlertLoadingView] hide];
    
    if (event && event.resultCode == 0) {
        self.msgArr = event;
        [_msgTableList reloadData];
        if (_msgArr.eventBoard.count > 0) {
            [_msgTableList scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_msgArr.eventBoard.count-1 inSection:0] atScrollPosition:UITableViewRowAnimationTop animated:NO];
        }
    }
    
}

- (void) didAddEventMsg:(EventBoardResponseMessage*)event
{
    if (event && event.resultCode == 0) {
        [_parser updateMsgWithId:_eventId];
    } else {
        [[iToast makeText:@"留言失败！"] show];
        [[GAlertLoadingView sharedAlertLoadingView] hide];
    }
}

- (void) didModifyEvent:(EventModifyResponseMessage*)event
{
    [[GAlertLoadingView sharedAlertLoadingView] hide];
    if (event && event.resultCode == 0) {
        [[iToast makeText:@"修改事件成功！"] show];
        [_builder release];
        _builder = nil;
        [self requestById:_eventId];
        [[EventManager sharedInstance] updateAllList];
    } else {
        [[iToast makeText:@"修改事件失败！"] show];
    }
}

- (void) didModifyEventMember:(EventMemberModifyResponseMessage *)event
{
    [[GAlertLoadingView sharedAlertLoadingView] hide];
    if (event && event.resultCode == 0) {
        [[iToast makeText:@"邀请成员成功！"] show];
        [_builder release];
        _builder = nil;
        [_canModifyFriends removeAllObjects];
        [self requestById:_eventId];
        //[[EventManager sharedInstance] updateAllList];
    } else {
        [[iToast makeText:@"邀请成员失败！"] show];
    }
}

- (void) didCreateEvent:(EventCreateResponseMessage*)event
{
    [[GAlertLoadingView sharedAlertLoadingView] hide];
    if (event && event.resultCode == 0 && event.eventId > 0) {
        [[iToast makeText:@"创建事件成功！"] show];
        [_builder release];
        _builder = nil;
        [[GAlertLoadingView sharedAlertLoadingView] show];
        [self requestById:event.eventId];
        [[EventManager sharedInstance] updateAllList];
    } else {
        [[iToast makeText:@"创建事件失败！"] show];
    }
}

- (void) didCancleEvent:(EventCancelResponseMessage*)event
{
    [[GAlertLoadingView sharedAlertLoadingView] hide];
    if (event && event.resultCode == 0) {
        
        NSDictionary * eventMsg = [self makePushMsg];
        [[MsgManager sharedInstance] removeMsg:eventMsg];
        
        [[iToast makeText:@"删除事件成功！"] show];
        [_builder release];
        _builder = nil;
        [[EventManager sharedInstance] updateAllList];
        [self dismiss];
    } else {
        [[iToast makeText:@"删除事件失败！"] show];
    }
}


#pragma mark - GridScrollDelegate

- (void) didSelect:(GridScrollView *)gridScroll atTotalIndex :(NSInteger)idx
{
    if (idx < _friendList.count)
    {
        EventMessage_UserStatus * userStat = [_friendList objectAtIndex:idx];
        FriendDetailViewController * detail = [[[FriendDetailViewController alloc] initWithNibName:@"FriendDetailViewController" bundle:nil] autorelease];
        
        [self.navigationController pushViewController:detail animated:YES];
        detail.activityBtn.hidden = YES;
        detail.btnDegree.hidden = YES;
        detail.btnDisagree.hidden = YES;
        
        if ([userStat isKindOfClass:[UserMessage class]]) {
            [detail updateUserStatus:(UserMessage*)userStat];
        } else {
            [detail updateUserStatus:userStat.user];
        }
        [detail doCheck];
    }
    else if ([self isEventOwner])
    {
        FriendSelViewController * selVC = [[[FriendSelViewController alloc] initWithNibName:@"FriendSelViewController" bundle:nil] autorelease];
        
        NSMutableArray * selIds = [NSMutableArray arrayWithCapacity:_canModifyFriends.count];
        for (EventMessage_UserStatus * status in _canModifyFriends) {
            if ([status isKindOfClass:[UserMessage class]]) {
                UserMessage * user = (UserMessage*)status;
                [selIds addObject:[NSNumber numberWithLongLong:user.id]];
            } else {
                [selIds addObject:[NSNumber numberWithLongLong:status.user.id]];
            }
        }
        selVC.selFriends = selIds;
        
        NSMutableArray * excludeIds = [NSMutableArray arrayWithCapacity:_friendList.count];
        for (EventMessage_UserStatus * status in _friendList) {
            if ([status isKindOfClass:[UserMessage class]]) {
                UserMessage * user = (UserMessage*)status;
                [excludeIds addObject:[NSNumber numberWithLongLong:user.id]];
            } else {
                [excludeIds addObject:[NSNumber numberWithLongLong:status.user.id]];
            }
        }
        selVC.excludeFriends = excludeIds;
        
        selVC.selDelegate = self;
        [self.navigationController pushViewController:selVC animated:YES];
    }
}


- (void)viewDidUnload {
    [self setGridScroll:nil];
    [self setUserListView:nil];
    [self setMsgText:nil];
    [self setContentScroll:nil];
    [self setMsgTableList:nil];
    [self setEventNameLabel:nil];
    [self setShopBtn:nil];
    [self setEventIcon:nil];
    [self setDateBtn:nil];
    [self setBtnSeeMsg:nil];
    [self setSetTopBtn:nil];
    [self setMemberLabel:nil];
    [super viewDidUnload];
}

- (void)moveViewForKeyboard:(NSNotification *)aNotification up:(BOOL)up
{
    NSDictionary *userInfo = [aNotification userInfo];
    
    NSTimeInterval animationDuration;
    UIViewAnimationCurve animationCurve;
    
    CGRect keyboardEndFrame;
    
    [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    
    [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardEndFrame];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    
    CGRect keyboardFrame = [self.view convertRect:keyboardEndFrame toView:nil];
    if (up) {
        _contentScroll.contentOffset = CGPointMake(0, keyboardFrame.size.height);
    } else {
        _contentScroll.contentOffset = CGPointZero;
    }

    [UIView commitAnimations];
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    if (![_eventNameLabel isFirstResponder]) {
        [self moveViewForKeyboard:aNotification up:YES];
    }
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    [self moveViewForKeyboard:aNotification up:NO];
}


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[_msgText resignFirstResponder];
}

#pragma mark - UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _msgArr.eventBoard.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EventBoardQueryResponseMessage_Board * msg = [_msgArr eventBoardAtIndex:indexPath.row];
    
    NSString * content = msg.content;
    CGSize sz = [content sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(220, 2000) lineBreakMode:NSLineBreakByCharWrapping];
    
    CGFloat height = sz.height + 40;
    NSLog(@"height = %f", height);
    
    return height < 80 ? 80 : height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EventBoardQueryResponseMessage_Board * msg = [_msgArr eventBoardAtIndex:indexPath.row];
    
    if ([GConfig getUserId] == msg.user.id) {
        static NSString *userMsgCellIdentifier = @"userMsgCellIdentifier";
        UserMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:userMsgCellIdentifier];
        if (cell == nil) {
            cell = [[[UserMsgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:userMsgCellIdentifier] autorelease];
        }
        
        [cell updateWithBoardMsg:msg];
        
        return cell;
    }
    
    static NSString *friendMsgCellIdentifier = @"friendMsgCellIdentifier";
    FriendMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:friendMsgCellIdentifier];
    if (cell == nil) {
        cell = [[[FriendMsgCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:friendMsgCellIdentifier] autorelease];
    }
    
    [cell updateWithBoardMsg:msg];
    
    return cell;
}

- (void) checkInitBuilder
{
    if (nil == _builder) {
        if (self.eventInfo) {
            _builder = [[self.eventInfo toBuilder] retain];
        } else {
            _builder = [[EventMessage builder] retain];
            self.eventInfo = [[[[[_builder setTime:[GToolUtil NSDateToFPDate:[NSDate date]]] setId:0] setOwner:[GToolUtil ownerMsg]] clone] build];
            [_dateBtn setTitle:[_formatter stringFromDate:[NSDate date]] forState:UIControlStateNormal];
        }
    }
}

- (void) checkDuplicated
{
    NSMutableSet * oldSet = [NSMutableSet setWithCapacity:4];
    for (EventMessage_UserStatus * status in _friendList) {
        if ([status isKindOfClass:[UserMessage class]]) {
            UserMessage * user = (UserMessage*)status;
            [oldSet addObject:[NSNumber numberWithLongLong:user.id]];
        } else {
            [oldSet addObject:[NSNumber numberWithLongLong:status.user.id]];
        }
    }
    
    NSMutableArray * removeObjs = [NSMutableArray arrayWithCapacity:2];
    for (EventMessage_UserStatus * status in _canModifyFriends) {
        if ([oldSet containsObject:[NSNumber numberWithLongLong:status.user.id]]) {
            [removeObjs addObject:status];
        }
    }
    
    for (EventMessage_UserStatus * status in removeObjs) {
        [_canModifyFriends removeObject:status];
    }
}

- (void) refreshDisplay
{
    if (_eventInfo) {
        [_friendList release];
        _friendList = [[GToolUtil PBArr2NSArr:_eventInfo.userStatus] retain];
        
        [self reloadGridScroll];
        
        if (!_eventInfo.image.isSys) {
            if ([[ImageManager sharedInstance] imageExistForId:_eventInfo.image.id]) {
                [_eventIcon setLocalImageName:[[ImageManager sharedInstance] imageFileForImageId:_eventInfo.image.id]];
            } else {
                [_eventIcon loadAsyncImage:_eventInfo.image.imageUrl];
            }
        } else {
            [_eventIcon setSysImageWithId:_eventInfo.image.id];
        }
        
        _eventNameLabel.text = _eventInfo.title;
        NSString * shopName = _eventInfo.merchant.name.length > 0 ? _eventInfo.merchant.name : @"点击选择商家";
        [_shopBtn setTitle:shopName forState:UIControlStateNormal];
        [_shopBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        NSDate * date = [[GToolUtil sharedInstance].dateFormatter dateFromString:[NSString stringWithFormat:@"%lld", _eventInfo.time]];
        
        [_dateBtn setTitle:[_formatter stringFromDate:date] forState:UIControlStateNormal];
    }
}


#pragma mark - CalendarPickDelegate

- (void)calendarDidPickDate:(NSDate*)date
{
    if (date) {
        long long newDate = [GToolUtil NSDateToFPDate:date];
        [self checkInitBuilder];
        [_dateBtn setTitle:[_formatter stringFromDate:date] forState:UIControlStateNormal];
        [_builder setTime:newDate];
    }
}


#pragma mark - ReminderDelegate

- (BOOL)didSelectSecondBefore:(NSInteger)seconds
{
    NSDate * eventDate = [[GToolUtil sharedInstance].dateFormatter dateFromString:[NSString stringWithFormat:@"%lld", _eventInfo.time]];
    NSString * eventKey = [NSString stringWithFormat:@"%lld", _eventId];

    if (seconds > 0) {
        NSDate * remindDate = [eventDate dateByAddingTimeInterval:-seconds];
        NSString * msg = [NSString stringWithFormat:@"离事件“%@”还有%@了", _eventNameLabel.text, [GToolUtil stringBySeconds:seconds]];
        [GReminder setReminder:[NSDictionary dictionaryWithObjectsAndKeys:msg, @"msg", I2N(seconds), @"secondsAgo", nil] at:remindDate withKey:eventKey];
        [[iToast makeText:@"闹钟已设置"] show];
    } else {
        [GReminder cancelReminderWithKey:eventKey];
        [[iToast makeText:@"闹钟已取消"] show];
    }
    return YES;
}


#pragma mark - FriendSelDelegate

- (void)didUpdateFriendSel:(NSMutableArray*)newSelFriends groupSel:(NSMutableArray *)selGroup
{
    if (newSelFriends) {
        [_canModifyFriends release];
        _canModifyFriends = [newSelFriends mutableCopy];
        
        NSMutableSet * oldSet = [NSMutableSet setWithCapacity:4];
        for (EventMessage_UserStatus * status in _canModifyFriends) {
            [oldSet addObject:[NSNumber numberWithLongLong:status.user.id]];
        }
        
        for (GroupMessage * msg in selGroup) {
            for (int i = 0; i < msg.users.count; i++) {
                UserMessage * userMsg = [msg usersAtIndex:i];
                EventMessage_UserStatus * status = [[[[EventMessage_UserStatus builder] setStatus:eStatWait] setUser:userMsg] build];
                if (status && ![oldSet containsObject:[NSNumber numberWithLongLong:status.user.id]]) {
                    [_canModifyFriends addObject:status];
                }
            }
        }
        
        [self checkDuplicated];
        
        [self reloadGridScroll];
    }
}

- (void)createWithPOI:(MerchantMessage *)msg
{
    if (msg) {
        [self checkInitBuilder];
        [_shopBtn setTitle:msg.name forState:UIControlStateNormal];
        [_builder setMerchant:msg];
        
        self.eventMode = eModeCreateEvent;
    }
}

#pragma mark - POISelDelegate

- (void)didSelPOI:(MerchantMessage*)msg
{
    if (msg) {
        [self checkInitBuilder];
        [_shopBtn setTitle:msg.name forState:UIControlStateNormal];
        [_shopBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_builder setMerchant:msg];
        
        if ([msg hasLogo] && ![_eventIcon isComplate]) {
            if (!msg.logo.isSys) {
                if ([[ImageManager sharedInstance] imageExistForId:msg.logo.id]) {
                    [_eventIcon setLocalImageName:[[ImageManager sharedInstance] imageFileForImageId:msg.logo.id]];
                } else {
                    [_eventIcon loadAsyncImage:msg.logo.imageUrl];
                }
            } else {
                [_eventIcon setSysImageWithId:msg.logo.id];
            }
            [_builder setImage:msg.logo];
        }
    }
}


#pragma mark - TemplateSelDelegate

- (BOOL)didSelTemplate:(EventMessage*)event
{
    if (event) {
        self.eventInfo = event;
        [self checkInitBuilder];
        [self refreshDisplay];
    }
    return YES;
}


#pragma mark - PickIconDelegate

- (void)didPickSysImage:(NSString*)sysImgName
{
    if (sysImgName) {
        [self checkInitBuilder];
        [_eventIcon setLocalImageName:sysImgName];
        
        BOOL isSys = [sysImgName hasPrefix:@"sys_"];
        NSString * imgId = [sysImgName substringFromIndex:4];
        NSInteger realId = [imgId integerValue];
        
        if (realId > 0 && isSys) {
            ImageMessage_Builder * imgBuilder = [[[ImageMessage builder] setId:realId] setIsSys:YES];
            ImageMessage * msg = [imgBuilder build];
            [_builder setImage:msg];
            return;
        }
    }
    [[iToast makeText:@"无效的系统图像!"] show];
}

- (void)didPickCustomImage:(long long)imgId
{
    if (imgId > 0) {
        [self checkInitBuilder];
        
        NSString * imgUrl = [[ImageManager sharedInstance] imageFileForImageId:imgId];
        [_eventIcon setLocalImageName:imgUrl];
        
        ImageMessage_Builder * imgBuilder = [[[ImageMessage builder] setId:imgId] setIsSys:NO];
        ImageMessage * msg = [imgBuilder build];
        [_builder setImage:msg];
        return;
    }
    [[iToast makeText:@"无效的系统图像!"] show];
}

@end
